import socket
import threading
import time
import matplotlib.pyplot as plt

response_times = []  # 用于存储每个请求的耗时

def send_request(client_id, server_address, server_port):
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((server_address, server_port))

    start_time = time.time()  # 记录请求开始时间

    request = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"
    client_socket.send(request.encode())

    response = client_socket.recv(1024).decode()
    print(f"Client {client_id} received response:\n{response}")

    end_time = time.time()  # 记录请求结束时间
    elapsed_time = end_time - start_time

    # 将耗时信息添加到全局列表中
    response_times.append(elapsed_time)

    client_socket.close()

def plot_response_times(response_times):
    plt.plot(response_times, marker='o')
    plt.title('Response Times for Each Request')
    plt.xlabel('Request Index')
    plt.ylabel('Elapsed Time (seconds)')
    plt.show()

def main():
    server_address = "192.168.254.130"  # 服务器的ip
    server_port = 8089  # 端口
    num_clients = 2000  # 发送请求数（修改这里）

    threads = []

    for i in range(num_clients):
        thread = threading.Thread(target=send_request, args=(i+1, server_address, server_port))
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

    # 绘制曲线图
    plot_response_times(response_times)

if __name__ == "__main__":
    main()

